package com.yicoollxing.controller.backend;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.yicoollxing.common.Const;
import com.yicoollxing.common.ServerResponse;
import com.yicoollxing.pojo.Food;
import com.yicoollxing.pojo.User;
import com.yicoollxing.service.IFileService;
import com.yicoollxing.service.IFoodService;
import com.yicoollxing.service.IUserService;
import com.yicoollxing.util.PropertiesUtil;

@Controller
@RequestMapping("/manager/food")
public class FoodManagerController {

	@Autowired
	private IUserService iUserService;

	@Autowired
	private IFoodService iFoodServie;

	@Autowired
	private IFileService iFileService;

	/**
	 * 商品管理（上下架，添加，更新功能，后台商品详情，后台商品列表，根据产品名或id查询，上传文件，上传富文本）
	 */

	/**
	 * 修改或添加食物
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/modify_add.do")
	public ServerResponse modifyAndAddFood(HttpSession session, Food food) {

		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}
		return iFoodServie.modifyAndAddFood(food);
	}

	@ResponseBody
	@RequestMapping("/modify_status.do")
	public ServerResponse setFoodStatus(Integer foodId, Integer status,
			HttpSession session) {

		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}
		return iFoodServie.setFoodStatus(foodId, status);
	}

	@ResponseBody
	@RequestMapping("/detail.do")
	public ServerResponse getFoodDetail(Integer foodId, HttpSession session) {

		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}
		return iFoodServie.getFoodDetail(foodId);
	}

	@ResponseBody
	@RequestMapping("/list.do")
	public ServerResponse getFoodList(
			Integer mid,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
			HttpSession session) {
		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}

		return iFoodServie.getFoodList(mid, pageNum, pageSize);
	}

	/**
	 * 通过id和名字查询商品，默认包含商户号
	 * 
	 * @param mid
	 * @param foodId
	 * @param foodName
	 * @param pageNum
	 * @param pageSize
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/query_id_orName.do")
	public ServerResponse queryFoodByIdOrName(
			Integer mid,
			Integer foodId,
			String foodName,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
			HttpSession session) {
		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}
		return iFoodServie.queryFoodByIdOrName(mid, foodId, foodName, pageNum,
				pageSize);
	}

	@ResponseBody
	@RequestMapping("/uplaod.do")
	public ServerResponse upload(
			HttpSession session,
			@RequestParam(value = "upload_file", required = false) MultipartFile file,
			HttpServletRequest request) {

		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			return ServerResponse.createByErrorMessage("请重新登录");
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			return response;
		}
		String pathtest = request.getContextPath();
		System.out.print(pathtest);
		String path = request.getSession().getServletContext().getContextPath();
		System.out.print(path);
		String targetFileName = iFileService.upload(file, path);
		if(targetFileName==null){
			return ServerResponse.createByErrorMessage("文件上传失败");
		}
		String url = PropertiesUtil.getProperty("ftp.server.http.prefix",
				"http://img.yicooll.com/") + targetFileName;
		Map map = Maps.newHashMap();
		map.put("uri", targetFileName);
		map.put("url", url);
		return ServerResponse.createBySuccess(map);
	}

	@ResponseBody
	@RequestMapping("/richtext_img_upload.do")
	public Map richTextImagUpload(
			HttpSession session,
			@RequestParam(value = "upload_file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse sevlertSresponse) {

		// 使用的是simditor 富文本 ，要按照规定的返回格式
		/**
		 * { "success":false/true, "msg":"error msg",
		 * "file_path":"file real path" }
		 */
		Map mapResult = Maps.newHashMap();
		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (user == null) {
			mapResult.put("success", false);
			mapResult.put("msg", "请重新登录");
			return mapResult;
		}
		ServerResponse response = iUserService.checkAdminRole(user);
		if (!response.isSuccess()) {
			mapResult.put("success", false);
			mapResult.put("msg", "无权限操作，需要管理员权限");
			return mapResult;
		}
		String path = request.getSession().getServletContext().getContextPath();
		String targetFileName = iFileService.upload(file, path);
		if(targetFileName==null){
			mapResult.put("success", false);
			mapResult.put("msg", "富文本上传失败");
			return mapResult;
		}
		String url = PropertiesUtil.getProperty("ftp.server.http.prefix",
				"http://img.yicooll.com/") + targetFileName;
		mapResult.put("success", true);
		mapResult.put("msg", "富文本上传成功");
		mapResult.put("file_path", url);
		// 返回前端框架需要的header 这里是约定好的，可以不加
		sevlertSresponse.addHeader("Acces-Control-Allow-Haads", "X-file-name");
		return mapResult;
	}

}
